package com.mti.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.component.snowflake.KeyWorker;
import com.mti.constant.AlarmFilterEnum;
import com.mti.dao.model.SysDictEntity;
import com.mti.dao.model.TSwitchTypeEntity;
import com.mti.dao.qo.KmAlarmFilterQo;
import com.mti.exception.BusinessException;
import com.mti.mapper.TSwitchTypeMapper;
import com.mti.service.ISysDictService;
import com.mti.service.TSwitchTypeServie;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author hf
 * @Title:
 * @Description: TODO (预警开关设置类)
 * @Param
 * @return
 * @Date 2020/11/24 10:12
 */
@Log4j2
@Service
public class TSwitchTypeServieImpl extends ServiceImpl<TSwitchTypeMapper, TSwitchTypeEntity> implements TSwitchTypeServie {

    @Autowired
    private ISysDictService iSysDictService;

    @Override
    public boolean upSertSwitchStatus(TSwitchTypeEntity tSwitchTypeEntity) {
        boolean flag = getSwitchStatus(tSwitchTypeEntity.getType(), tSwitchTypeEntity.getName());
        UpdateWrapper<TSwitchTypeEntity> wrapper = new UpdateWrapper<TSwitchTypeEntity>();
        if (StringUtils.isEmpty(tSwitchTypeEntity.getKey())) {
            wrapper.eq("name", tSwitchTypeEntity.getName()).eq("parent_key", tSwitchTypeEntity.getParentKey()).eq("type", tSwitchTypeEntity.getType());
        } else {
            wrapper.eq("name", tSwitchTypeEntity.getName()).eq("parent_key", tSwitchTypeEntity.getParentKey()).eq("type", tSwitchTypeEntity.getType()).eq("key", tSwitchTypeEntity.getKey());
        }
        if (StringUtils.isEmpty(tSwitchTypeEntity.getDescribe())) {
            wrapper.set("status", !flag);
        } else {
            wrapper.set("status", !flag).set("describe", tSwitchTypeEntity.getDescribe());
        }
        return this.update(wrapper);
    }

    @Override
    public boolean getSwitchStatus(int type, String name) {
        TSwitchTypeEntity tSwitchTypeEntity = this.getOne(new QueryWrapper<TSwitchTypeEntity>().eq("type", type).eq("name", name).lambda().last("LIMIT 1"));
        if (null == tSwitchTypeEntity) {
            TSwitchTypeEntity entity = new TSwitchTypeEntity();
            entity.setId(String.valueOf(KeyWorker.nextId()));
            entity.setName(name);
            entity.setType(type);
            entity.setStatus(false);
            this.save(entity);
            return false;
        }
        return tSwitchTypeEntity.isStatus();
    }

    @Override
    public Map getSwitchByType(List typeList, String name) {
        Map<String, List<TSwitchTypeEntity>> data = this.getBaseMapper().getSwitchByName(typeList, name).stream().collect(Collectors.groupingBy(TSwitchTypeEntity::getParentKey));
        List<TSwitchTypeEntity> list = data.get(AlarmFilterEnum.RYLX_ALARM.getKey());
        if (!Collections.isEmpty(list)) {
            list.forEach(e -> {
                List<TSwitchTypeEntity> cList = this.getBaseMapper().getByParentKey(e.getKey());
                e.setChildren(cList);
            });
        }
        return data;
    }

    @Override
    public void initYjManageInfo() {
        this.remove(new QueryWrapper<>());
        List<TSwitchTypeEntity> list = AlarmFilterEnum.toYjfsList();
        Map<String, List<SysDictEntity>> data = iSysDictService.list(new QueryWrapper<SysDictEntity>().isNotNull("type_")).stream().collect(Collectors.groupingBy(SysDictEntity::getType));
        List<TSwitchTypeEntity> tlist = AlarmFilterEnum.toList();
        tlist.forEach(ts -> {
            List<SysDictEntity> myData = data.get(ts.getKey());
            if (!Collections.isEmpty(myData)) {
                List<SysDictEntity> result = myData.stream().filter(e -> !ObjectUtils.isEmpty(e)).collect(Collectors.toList());
                result.forEach(e -> {
                    TSwitchTypeEntity tSwitchTypeEntity = new TSwitchTypeEntity();
                    tSwitchTypeEntity.setName(e.getValue());
                    tSwitchTypeEntity.setDescribe(ts.getDescribe());
                    tSwitchTypeEntity.setType(ts.getType());
                    tSwitchTypeEntity.setKey(e.getKey());
                    tSwitchTypeEntity.setParentKey(ts.getKey());
                    tSwitchTypeEntity.setStatus(false);
                    tSwitchTypeEntity.setId(String.valueOf(KeyWorker.nextId()));
                    list.add(tSwitchTypeEntity);
                });
            }
        });
        List<SysDictEntity> sonOfRylbList = iSysDictService.list(new QueryWrapper<SysDictEntity>().eq("type_", AlarmFilterEnum.RYLX_ALARM.getKey()).isNotNull("type_")).stream().collect(Collectors.toList());
        sonOfRylbList.forEach(e -> {
            List<SysDictEntity> mylist = iSysDictService.list(new QueryWrapper<SysDictEntity>().eq("type_", e.getKey()).isNotNull("type_")).stream().collect(Collectors.toList());
            mylist.forEach(d -> {
                TSwitchTypeEntity tSwitchTypeEntity = new TSwitchTypeEntity();
                tSwitchTypeEntity.setName(d.getValue());
                tSwitchTypeEntity.setDescribe(e.getValue());
                tSwitchTypeEntity.setType(2);
                tSwitchTypeEntity.setParentKey(e.getKey());
                tSwitchTypeEntity.setKey(d.getKey());
                tSwitchTypeEntity.setStatus(false);
                tSwitchTypeEntity.setId(String.valueOf(KeyWorker.nextId()));
                list.add(tSwitchTypeEntity);
            });
        });
        this.saveBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveList(List<TSwitchTypeEntity> list) {
        list.forEach(e -> {
            //找不到就新增
            TSwitchTypeEntity tSwitchTypeEntity = new TSwitchTypeEntity();
            tSwitchTypeEntity.setKey(e.getKey());
            tSwitchTypeEntity.setName(e.getName());
            tSwitchTypeEntity.setDescribe(e.getDescribe());
            tSwitchTypeEntity.setType(e.getType());
            tSwitchTypeEntity.setStatus(e.isStatus());
            tSwitchTypeEntity.setParentKey(e.getParentKey());
            tSwitchTypeEntity.setId(String.valueOf(KeyWorker.nextId()));
            this.save(tSwitchTypeEntity);
        });
    }

    @Override
    public KmAlarmFilterQo getQoInfo(List<Integer> typeList) {
        KmAlarmFilterQo kmZdryPushToDsQo = new KmAlarmFilterQo();
        try {
            Map<String, List<TSwitchTypeEntity>> map = this.getBaseMapper().getSwitchByName(typeList, null).stream().collect(Collectors.groupingBy(TSwitchTypeEntity::getParentKey));
            //预警方式
            if (!Collections.isEmpty(map.get(AlarmFilterEnum.TLGP_ALARM.getKey()))) {
                kmZdryPushToDsQo.setYjlxList(map.get(AlarmFilterEnum.TLGP_ALARM.getKey()).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList()));
            }
            //稳控状态
            if (!Collections.isEmpty(map.get(AlarmFilterEnum.WKZT_ALARM.getKey()))) {
                kmZdryPushToDsQo.setWkztList(map.get(AlarmFilterEnum.WKZT_ALARM.getKey()).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList()));
            }
            //预警处置类别
            if (!Collections.isEmpty(map.get(AlarmFilterEnum.YJCZLB_ALARM.getKey()))) {
                kmZdryPushToDsQo.setYjczlbList(map.get(AlarmFilterEnum.YJCZLB_ALARM.getKey()).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList()));
            }
            //风险等级
            if (!Collections.isEmpty(map.get(AlarmFilterEnum.FXDJ_ALARM.getKey()))) {
                kmZdryPushToDsQo.setFxdjList(map.get(AlarmFilterEnum.FXDJ_ALARM.getKey()).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList()));
            }
            //人员类型-大类
            if (!Collections.isEmpty(map.get(AlarmFilterEnum.RYLX_ALARM.getKey()))) {
                kmZdryPushToDsQo.setRylxList(map.get(AlarmFilterEnum.RYLX_ALARM.getKey()).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList()));
            }
            //对应警种
            if (!Collections.isEmpty(map.get(AlarmFilterEnum.DYJZ_ALARM.getKey()))) {
                kmZdryPushToDsQo.setZrbmList(map.get(AlarmFilterEnum.DYJZ_ALARM.getKey()).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList()));
            }
            //管控责任州市
            if (!Collections.isEmpty(map.get(AlarmFilterEnum.GKZRZS_ALARM.getKey()))) {
                kmZdryPushToDsQo.setSszsmcList(map.get(AlarmFilterEnum.GKZRZS_ALARM.getKey()).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList()));
            }
            //管控责任分局
            if (!Collections.isEmpty(map.get(AlarmFilterEnum.GKZRFJ_ALARM.getKey()))) {
                kmZdryPushToDsQo.setSsxqList(map.get(AlarmFilterEnum.GKZRFJ_ALARM.getKey()).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList()));
            }
            List<String> list = this.list(new QueryWrapper<TSwitchTypeEntity>().eq("parent_key", AlarmFilterEnum.RYLX_ALARM.getKey())).stream().filter(e -> e.isStatus() == true).map(TSwitchTypeEntity::getKey).collect(Collectors.toList());
            if (!Collections.isEmpty(list)) {
                List<String> names = this.list(new QueryWrapper<TSwitchTypeEntity>().select().in("parent_key", list)).stream().filter(e -> e.isStatus()).map(TSwitchTypeEntity::getName).collect(Collectors.toList());
                //人员类型-小类
                kmZdryPushToDsQo.setSonRylxList(names);
            }
            TSwitchTypeEntity startEntity = this.getOne(new QueryWrapper<TSwitchTypeEntity>().eq("parent_key", AlarmFilterEnum.START_TIME.getKey()));
            kmZdryPushToDsQo.setStartTime(startEntity == null ? null : startEntity.getName());
            TSwitchTypeEntity endEntity = this.getOne(new QueryWrapper<TSwitchTypeEntity>().eq("parent_key", AlarmFilterEnum.END_TIME.getKey()));
            kmZdryPushToDsQo.setEndTime(startEntity == null ? null : endEntity.getName());

            return kmZdryPushToDsQo;
        } catch (Exception e) {
            log.error("获取搜索条件失败", e);
            throw new BusinessException(10020, "获取搜索条件失败");
        }
    }

    @Override
    public void setTime(String startTime, String endTime) {
        if (!StringUtils.isEmpty(startTime)) {
            String id = this.getBaseMapper().getTimeKey(AlarmFilterEnum.START_TIME.getKey());
            TSwitchTypeEntity entity = new TSwitchTypeEntity();
            entity.setId(id);
            entity.setParentKey(AlarmFilterEnum.START_TIME.getKey());
            entity.setKey(AlarmFilterEnum.START_TIME.getKey());
            entity.setType(AlarmFilterEnum.START_TIME.getType());
            entity.setDescribe(AlarmFilterEnum.START_TIME.getDesc());
            entity.setName(startTime);
            this.saveOrUpdate(entity);
        }
        if (!StringUtils.isEmpty(endTime)) {
            String id = this.getBaseMapper().getTimeKey(AlarmFilterEnum.END_TIME.getKey());
            TSwitchTypeEntity entity = new TSwitchTypeEntity();
            entity.setId(id);
            entity.setParentKey(AlarmFilterEnum.END_TIME.getKey());
            entity.setKey(AlarmFilterEnum.END_TIME.getKey());
            entity.setType(AlarmFilterEnum.END_TIME.getType());
            entity.setDescribe(AlarmFilterEnum.END_TIME.getDesc());
            entity.setName(endTime);
            this.saveOrUpdate(entity);
        }

    }
}
